#include <unordered_map>
#include<string.h>
#include <pthread.h>
#include "tcpsocket.hpp"
using namespace std;

unordered_map<string, string> table = {
  {"hello", "你好"},
  {"hi", "雷猴"},
  {"吃了吗", "油泼面"}

};

string get_response(const string &key) {
  string rsp;
  auto it = table.find(key);
  if (it == table.end()) {
    rsp = "未知请求";
    return rsp;

  }
  rsp = it->second;
  return rsp;

}

void *thr_entry(void *arg)
{
 TcpSocket *sock = (TcpSocket*)arg;
  //TcpSocket sock;
  //sock->SetFd(*(int*)&arg);
  while(1) {
    string buf;
    sock->Recv(&buf);
    cout << "client request: " << buf << endl;
    string rsp = get_response(buf);
    sock->Send(rsp);
  }
  //delete sock;
  return NULL;
}
void CreateWorker(TcpSocket &sock)
{
  pthread_t tid;
  //int sockfd = sock.GetFd();
  int ret = pthread_create(&tid, NULL, thr_entry, (void*)&sock);
  if (ret != 0) {
    cout << "create thread failed!\n";
    return ;
  }
  pthread_detach(tid);
  return ;
}
int main(int argc, char *argv[])
{
  if (argc < 2) {
    cout << "usage: ./tcp_srv 9000\n";
    return -1;
  }
  int port = std::stoi(argv[1]);
  TcpSocket lst_sock;
  //创建套接字
  CHECK_RET(lst_sock.Socket());
  //绑定地址信息, "0.0.0.0"会被识别为本机上任意网卡IP地址--绑定0.0.0.0就表示绑定了本机上所有网卡
  CHECK_RET(lst_sock.Bind("0.0.0.0", port));
  //开始监听
  CHECK_RET(lst_sock.Listen());
  while(1) {
    //获取新建连接,获取了与哪个客户端新建的连接，则与哪个客户端进行通信
    //TcpSocket *new_sock = new TcpSocket();//这是一个局部变量，在本次循环完毕就会被释放
    TcpSocket new_sock;
    string cli_ip;
    int cli_port;
    CHECK_RET(lst_sock.Accept(&new_sock, &cli_ip, &cli_port));
    cout << "new connect: " << cli_ip << ":" << cli_port << "\n";
    //创建一个执行流，专门负责一个客户端的通信
    CreateWorker(new_sock);
  }
  //关闭套接字
  lst_sock.Close();
  return 0;
}








